//
//  XFOauthViewController.swift
//  mxfweibo
//
//  Created by apple1 on 15/12/19.
//  Copyright © 2015年 莫祥富. All rights reserved.
//

import UIKit

import SVProgressHUD

class XFOauthViewController: UIViewController ,UIWebViewDelegate{

    
    //MARK: - webView代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!.absoluteString
        
        if !url.hasPrefix(XFNetworkTool.sharedInstance.redirect_uri) {
            
            return true
        }
        
        //获取URL中？后面的内容
        if let query = request.URL?.query {
            
            let codeString = "code="
            
            //判断query是否以code＝开头
            if query.hasPrefix(codeString){
                
                let queryNS = query as NSString
                
                let code = queryNS.substringFromIndex(codeString.characters.count)
                
                print("code = \(code)")
                
                loadAccessToken(code)
                
            }else{
                self.cancel()
            }
            
            
        }else{
            print("query没有值")
        }
        
        
        return false
    }
    
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = XFNetworkTool.sharedInstance.oAuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.title = "登录"
    }

    //填充帐号密码
    func autoFill(){
        let js = "document.getElementById('userId').value='18172641885@163.com'; document.getElementById('passwd').value='3232527';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //取消
    func cancel(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 加载AccessToken
    func loadAccessToken(code:String){
        
        XFNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            if error != nil && result == nil{
                
                print("error:\(error)")
                
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
                self.cancel()
                return
            }
           
            let userAccount = XFUserAccount(dict: result!)
            
            userAccount.saveUserAccount()
            
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
        }
    }
    
    
    private lazy var webView = UIWebView()

}
